package se.vgregion.icc;

import static org.junit.Assert.assertTrue;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/***
 * Handles assertions of timespan tests on various test methods.
 * 
 * @author ricra2 & angin40
 */
public final class TimeAssertHandler {

    private TimeAssertHandler() {
    }

    private static final int REASONABLE_TIMEDIFF = 999;
    public static final String TIMESPAN_ASSERT_DESCRIPTION = "Expected -" + REASONABLE_TIMEDIFF + " < timespan < "
        + REASONABLE_TIMEDIFF + ", was ";

    /***
     * Asserts if the span is within the acceptable time diff.
     *
     * @param pingTime Date object from right before the test.
     * @param pingResponseTime String representation of Date from the componentPing.
     * @throws ParseException - if String representation is invalid.
     */
    public static void assertReasonablePingTime(Date pingTime, String pingResponseTime) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        long span = formatter.parse(pingResponseTime).getTime() - pingTime.getTime();
        assertTrue(TIMESPAN_ASSERT_DESCRIPTION + span, checkReasonableTimespan(span));
    }

    /***
     *Check if the timespan is within the reasonable time diff. 
     *
     * @param span the acceptable actual span of the ping.
     * @return true if span is between the reasonable time diff, else false.
     */
    private static boolean checkReasonableTimespan(long span) {
        return span < REASONABLE_TIMEDIFF && span > -REASONABLE_TIMEDIFF;
    }
}
